<template>
  <div class="app-container">
    <Header />
    <div class="main-container" style="justify-content: flex-start;overflow: auto;">
      <div class="px-4 py-[6px] rounded-[6px] text-[#000]  flex items-center cursor-pointer" @click="goBack">
        <el-icon class="mr-1">
          <Back />
        </el-icon>
        返回
      </div>
      <!-- 考核信息卡片 -->
      <div class="assessment-card">
        <div class="assessment-header">
          <div class="left flex">
            <img :src="listdetaile.cover" alt="课程封面" class="cover-img">
            <div class="info">
              <div class="flex">
                <div class="title flex1 flex">
                  <span>{{ listdetaile.name }}</span>
                  <div class="level">{{ listdetaile.level }}级</div>
                  <!-- <img src="@/assets/home/aji.png"  class="progress-img"> -->
                </div>
                <div class="flex">
                  <div class="countdown flex" v-if="isCountdownActive()">
                    <img src="@/assets/home/daojishi.png" alt="倒计时" class="clock-img">
                    <span>倒计时：</span>
                    <span>
                      <el-countdown :value="endTime" format="DD[天]HH[小时]mm[分钟]"/>
                    </span>
                    <!-- <span v-else>已结束</span> -->
                  </div>
                  <div v-if="isCountdownActive() && list.length > 0">
                    <el-button type="primary" v-if="assessmentDetails.status == 2" @click="handleCardClick(list[0])">开始考核</el-button>
                    <el-button type="primary" v-if="assessmentDetails.status == 1" @click="handleCardClick(list[0])">重新考核</el-button>
                    <el-button type="primary" v-if="assessmentDetails.status == 0" @click="handleCardClick('')">继续考核</el-button>
                  </div>
                </div>
              </div>
              <div class="detail-rows">
                <div class="flex">
                  <div class="detail-row flex">
                    <div class="text-custom-text-45 mr-11">所属岗位：<span class="text-custom-text">{{ listdetaile.job }}</span></div>
                    <div class="flex text-custom-text-45 mr-11">
                      试卷来源：
                      <span v-if="listdetaile.source == 'class'" class="text-custom-text">班期</span>
                      <span v-if="listdetaile.source == 'company'" class="text-custom-text">企业</span>
                      <span v-if="listdetaile.source == 'self'" class="text-custom-text">自选考核库</span>
                    </div>
                    <div class="text-custom-text-45 mr-11">考核总得分： <span class="text-custom-text">{{ listdetaile.score }} / {{ listdetaile.paper_score }} 分</span>  </div>
                    <div class="text-custom-text-45">建议时长： <span class="text-custom-text">{{ listdetaile.duration }}分钟</span></div>
                  </div>
                </div>
                <div class="detail-row">
                  <div class="text-custom-text-45">有效期限：<span class="text-custom-text">{{(listdetaile.range_date && listdetaile.range_date[0]) ? listdetaile.range_date[0] : '-' }} 至 {{(listdetaile.range_date && listdetaile.range_date[1]) ? listdetaile.range_date[1] : '-' }}</span></div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="chapter-scores">
          <el-table :data="[listdetaile.chapter_score]" style="width: 100%" border>
            <el-table-column label="章节名称" width="120">
              <template #header="scope"><span class="text-custom-text-45">章节名称</span></template>
              <template #default="scope"><span class="text-custom-text-45">章节得分</span></template>
            </el-table-column>
            <el-table-column v-for="(score, index) in listdetaile.chapter_score" :key="index" :label="score.name">
              <template #header>
                <span class="text-custom-text">{{ score.name }}</span>
              </template>
              <template #default>
                <span class="text-custom-text">{{ score.score == 0 ? 0 : score.score || '-' }}</span>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <!-- 章节详情列表 -->
      <div class="chapter-list">
        <div class="list-header">
          <span class="title flex">
            <div class="gun"></div>章节详情
          </span>
          <span class="progress flex">
            <img src="@/assets/home/time.png" alt="进度条">
            {{ listdetaile.process }}%</span>
        </div>
        <div class="chapter-grid">
          <div class="chapter-item" v-for="(item, index) in list" :key="item.id" @click="handleCardClick(item)">
            <div class="status-tags">
              <span class="status-tag" v-if="item.status == 0">待通关</span>
              <span class="status-tag" v-if="item.status == 1"
                style="background: linear-gradient( 135deg, #69E3AC 0%, #19B21E 100%);">已通关</span>
              <span class="status-tag" v-if="item.status == -1"
                style="background: linear-gradient( 135deg, #FCB191 0%, #FC474C 100%);">未通关</span>
              <span class="action-tag" v-if="item.ctype">{{ item.ctype }}</span>
            </div>
            <img :src="item.cover" alt="章节图片" class="chapter-img">
            <div class="chapter-info">
              <div class="chapter-title flex">
                <div class="flex1">{{ item.name }}</div>
                <img src="@/assets/home/xing.png" v-for="i in item.level">
              </div>
              <div class="score-row">
                <span>得分：{{ item.score }} / {{ item.total_score }} </span>
                <span>建议时长：{{ item.duration }}分钟</span>
              </div>
              <div class="time-row">
                <span>考核时间：{{ filterTime(item.exam_time) }}</span>
              </div>
              <div class="time-row">
                <span>上次考核：{{ item.last_exam_time }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, onUnmounted } from 'vue'
import { useRoute, useRouter } from 'vue-router';
import { userApi } from '@/api/modules/user.js'
import { StorageUtil } from '@/utils/common.js'
import dayjs from 'dayjs'
import Header from '@/components/layout/Header.vue'
const router = useRouter();
const route = useRoute();
const testId = ref('');
const endTime = ref(0)
const startTime = ref(0)
const list = ref([])
const listdetaile = ref({})
onMounted(() => {
  testId.value = route.params.testId;
  fetchAssessmentDetails();
  getStudentchapterRecordDetails()
});
onUnmounted(() => {
  sessionStorage.removeItem('AssessmentDetails')
})
const assessmentDetails = computed(() => {
  const obj = sessionStorage.getItem('AssessmentDetails')
  return JSON.parse(obj)
})

const handleCardClick = (item) => {
  // 如果不在有效时间内，直接返回
  if (!isCountdownActive()) {
    return
  }
  
  // 如果没有传入 item，则根据来源类型查找未完成的章节
  if (!item) {
    const filterCondition = listdetaile.value.source == 'company' 
      ? (chapter => chapter.status == 0)  // 企业来源只查找待通关的章节
      : (chapter => chapter.status == 0 || chapter.status == -1)  // 其他来源查找待通关或未通关的章节
    
    const unDoneList = list.value.filter(filterCondition)
    item = unDoneList[0]
    // 企业来源且没有找到待通关章节，或者没有找到任何章节，直接返回
    if (!item || (listdetaile.value.source == 'company' && item.status != 0)) {
      return
    }
  }else {
    if (listdetaile.value.source == 'company' && item.status != 0) {
      return    
    }
  }
  // 存储章节数据并跳转
  StorageUtil.session.set('paperData', item)
  router.push({
    path: '/examCourses/chapterDetail',
    query: {
      paperId: listdetaile.value.id,
      chapterId: item.id,
      test_id: assessmentDetails.value.test_id,
    }
  })
}
// 
const filterTime = (exam_time) => {
  if (exam_time && Array.isArray(exam_time) && exam_time.length === 2) {
    let start = dayjs(exam_time[0]).format('YYYY-MM-DD HH:mm');
    let end = dayjs(exam_time[1]).format('HH:mm'); // 只保留小时和分钟
    let result = `${start} - ${end}`;
    return result
  } else {
    return '-'
  }
}
// 获取结束时间的时间戳
function getEndDateTimestamp(time) {
  return dayjs(time).valueOf();
}
const isCountdownActive = () => {
  const now = dayjs();
  const start = dayjs(startTime.value);
  const end = dayjs(endTime.value);
  // 判断当前时间是否在开始时间和结束时间之间
  return now.isAfter(start) && now.isBefore(end);
};
const fetchAssessmentDetails = async () => {
  try {
    const data = await userApi.getStudentExamRecordDetail(testId.value);
    listdetaile.value = data
    if (data.range_date && data.range_date[1]) {
      startTime.value = getEndDateTimestamp(data.range_date[0])
      endTime.value = getEndDateTimestamp(data.range_date[1])
    }
  } catch (err) {
    console.log('Failed to fetch data:', err);
  }
};
const getStudentchapterRecordDetails = async () => {
  try {
    const data = await userApi.getStudentchapterRecord(testId.value);
    list.value = data || []
  } catch (err) {
    console.log('Failed to fetch data:', err);
  }
};
const goBack = () => {
  router.back()
}
</script>

<style lang="scss" scoped>
    .app-container{
      height: 100%;
      overflow: hidden;
      display: flex;
      flex-direction: column;
    }
:deep(.el-statistic__number) {
  background: rgba(51, 160, 255, 0.08);
  color: #33A0FF;
  padding: 2px 5px;
  border-radius: 2px;
  font-size: 16px;
  font-weight: bold;
}

.chapter-scores {
  margin-top: 24px;
  padding-top: 24px;
  border-top: 1px solid #F0F0F0;

  :deep(.el-table) {
    .el-table__header {
      th {
        // background-color: #F5F5F5;
        color: rgba(0, 0, 0, 0.85);
        font-weight: normal;
        font-size: 14px;
        text-align: left;
        padding-left: 16px;
      }
    }

    .el-table__body {
      td {
        padding: 12px 16px;
        font-size: 14px;
        color: rgba(0, 0, 0, 0.65);
        text-align: left;
      }
    }
  }
}

.main-container {
  height: calc(100% - 60px);
  padding: 32px 10%;
  background-color: #F5F5F5;
  // min-height: 100vh;
  flex-direction: column;
  margin-top: 60px;;
}

.assessment-card {
  background: #FFFFFF;
  border-radius: 6px;
  padding: 24px;
  margin-bottom: 24px;

  .assessment-header {
    display: flex;
    justify-content: space-between;

    .info {
      flex: 1;
    }

    .left {
      display: flex;
      gap: 24px;
      width: 100%;

      .cover-img {
        max-width: 180px;
        height: 142px;
        border-radius: 4px;
      }

      .info {
        .countdown {
          margin-right: 16px !important;

          span {
            padding: 0 10px;
            line-height: 30px;
          }

          img {
            width: 16px;
            height: 16px;
            margin-top: 7px;
          }

          .time {
            background: #F5F5F5;
            padding: 2px 8px;
            margin: 0 4px;
            border-radius: 2px;
            color: #1890FF;
          }
        }

        .title {
          font-size: 20px;
          font-weight: 500;

          .level {
            width: 36px;
            height: 22px;
            background-color: #FFF4F4;
            text-align: center;
            font-family: MiSans, MiSans;
            font-weight: 400;
            font-size: 12px;
            margin-top: 5px;
            color: #FC474C;
            margin-left: 10px;
            line-height: 22px;
          }

          .progress-img {
            margin-left: 10px;
            width: 36px;
            height: 22px;
            margin-top: 5px;
          }

          .tag {
            background: #FF4D4F;
            color: #fff;
            padding: 2px 8px;
            border-radius: 2px;
            font-size: 12px;
            margin-left: 8px;
          }
        }

        .detail-rows {
          margin-top: 16px;
          background-color: #F5F5F5;
          padding: 16px;
          border-radius: 6px 6px 6px 6px;
        }

        .detail-row {
          color: rgba(0, 0, 0, 0.65);
          margin-bottom: 8px;
          font-size: 14px;

          span+span {
            margin-left: 24px;
          }
        }
      }
    }


  }


}

.chapter-list {
  // background: #FFFFFF;
  border-radius: 6px;
  // padding: 24px 0;

  .list-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;

    .gun {
      width: 4px;
      height: 20px;
      background: linear-gradient(180deg, #9DD1FF 0%, #33A0FF 100%);
      border-radius: 1px 1px 1px 1px;
      margin-right: 12px;
    }

    .title {
      font-size: 18px;
      font-weight: bold;

    }

    .progress {
      img {
        width: 20px;
        height: 20px;
        margin-right: 7px;
      }

      font-size: 16px;
      color: rgba(0, 0, 0, 0.88);
    }
  }

  .chapter-grid {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 24px;

    .chapter-item {
      border: 1px solid #F0F0F0;
      border-radius: 4px;
      overflow: hidden;
      background: #FFFFFF;
      cursor: pointer;
      position: relative;

      .status-tags {
        position: absolute;
        display: flex;
        gap: 8px;
        padding: 8px;


        .status-tag {
          padding: 2px 8px;
          border-radius: 2px;
          font-size: 12px;
          background: linear-gradient(135deg, #F4E377 0%, #FA9600 100%);
          color: #fff;

          &.waiting {
            background: #FAAD14;
            color: #fff;
          }
        }

        .action-tag {
          background: #1890FF;
          color: #fff;
          padding: 2px 8px;
          border-radius: 2px;
          font-size: 12px;
        }
      }

      .chapter-img {
        width: 100%;
        height: 160px;
        object-fit: cover;
      }

      .chapter-info {
        padding: 16px;

        .chapter-title {
          font-weight: 500;
          margin-bottom: 12px;

          img {
            width: 20px;
            height: 20px;
            margin-left: 7px;
          }
        }

        .score-row,
        .time-row {
          color: rgba(0, 0, 0, 0.65);
          font-size: 14px;
          margin-bottom: 8px;

          span+span {
            margin-left: 16px;
          }
        }
      }
    }
  }
}
</style>
